var BillId = RequestURLParam.getParam("billId");
var Path = decodeURIComponent(RequestURLParam.getParam("path"));
var uploader;
$(function() {
    var $list = $("#thelist");
    var $btn = $("#ctlBtn");
    var state = 'pending'; // 上传文件初始化
    uploader = WebUploader.create({
        swf : '/common/webuploader/Uploader.swf',
        server : 'uploadFile/upload.do',
        pick : '#picker',
        threads:1,//上传并发数。允许同时最大上传进程数。
        formData:{"BillId":BillId,"Path":Path},
        resize : false
    });
    uploader.on('fileQueued', function(file) {
        $list.append('<div id="' + file.id + '" class="item">'
            + '<button  class="btn btn-danger" style="float: right;margin-right: 10px;" onclick="RemoveFile(\''+file.id+'\')">删除</button>'
            + '<h4 class="info">' + file.name + '</h4>'
            + '<p> <span class="state">等待上传...</span><span class="per">0%</span>'
            + '</p>' + '</div>');
        var $li = $('#' + file.id);
        var $percent = $('<div class="progress progress-striped active">'
            + '<div class="progress-bar" role="progressbar" style="width: 0%">'
            + '</div>' + '</div>').appendTo($li).find('.progress-bar');
    });

    uploader.on('uploadProgress',
        function(file, percentage) {
            var $li = $('#' + file.id);
            var $percent = $li.find('.progress .progress-bar');
            $li.find('span.state').text('上传中...');
            $li.find('span.per').text( percentage * 100 + '%');
            $percent.css('width', percentage * 100 + '%');
        });


    uploader.on('uploadSuccess', function(file,data) {
        $('#' + file.id).find('button.btn').attr('onclick',"del('"+file.id+"','"+data.fileID+"')");
        $('#' + file.id).find('span.state').text('已上传...');
    });

    uploader.on('uploadError', function(file) {
        $('#' + file.id).find('span.state').text('上传出错...');
    });

    uploader.on('uploadComplete', function(file) {
        $('#' + file.id).find('.progress').fadeOut();
    });
    $btn.on('click', function() {
        if (state === 'uploading') {
            uploader.stop();
        } else {
            uploader.upload();
        }
    });

});

function confirm() {
    window.CloseOwnerWindow("OK");
}

function RemoveFile(file) {
    uploader.removeFile(file);
    $("#"+file).remove();
}

function del(file,fileId){
    deletefile(fileId);
    $("#"+file).remove();
}